import os
from datetime import datetime, timedelta
from flask import (
    render_template,
    request,
    flash,
    redirect,
    url_for,
    jsonify,
    g,
    send_from_directory,
    Blueprint,
)
from models import app, User, Jobnumber, Category, Subcategory, Task, db
from sqlalchemy.sql import func, extract
from flask_login import (
    LoginManager,
    login_required,
    login_user,
    logout_user,
    current_user,
)
from flask_wtf import FlaskForm
from functools import wraps
from bp_admin import bp_admin
from bp_assess import bp_assess
from bp_user import bp_user
from bp_plot import bp_plot
from bp_partner import bp_partner
from bp_tool import bp_tool
from bp_todo import bp_todo


nginx = "/task"

app.register_blueprint(bp_admin, url_prefix=nginx + "/admin")
app.register_blueprint(bp_user, url_prefix=nginx + "/user")
app.register_blueprint(bp_assess, url_prefix=nginx + "/assess")
app.register_blueprint(bp_plot, url_prefix=nginx + "/plot")
app.register_blueprint(bp_partner, url_prefix=nginx + "/partner")
app.register_blueprint(bp_tool, url_prefix=nginx + "/tool")
app.register_blueprint(bp_todo, url_prefix=nginx + "/todo")


# @app.context_processor
# def inject_cdn():
#     # g.cdn="https://cdnjs.cloudflare.com/ajax/libs/"
#     g.cdn = "http://192.168.67.111/cdn/"
#     return dict(cdn=g.cdn)


# @app.route(nginx + "/static/<path:path>")
# def send_js(path):
#     print(path)
#     return send_from_directory("task/static", path)


login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
login_manager.login_message = "请先登陆"
login_manager.login_message_category = "warning"


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


@app.route(nginx + "/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    if request.method == "POST":
        no = request.form.get("no").strip()
        password = request.form.get("password").strip()

        user = User.query.filter_by(no=no).first()
        if not user:
            flash("工号{}不存在。".format(no), category="danger")
            return redirect(url_for("login"), code=302)

        if user.delete:
            flash("账号 {} 被禁用。".format(no), category="danger")
            return redirect(url_for("login"), code=302)

        if not user.check_password(password):
            flash("密码错误", category="danger")
            flash("重置密码请联系金曼", category="warning")
            return redirect(url_for("login"), code=302)
        login_user(user)
        # if password in ["1", "123456"]:
        #     flash("登陆成功!", category="success")
        #     flash("请修改初始密码", category="warning")
        #     return redirect(url_for("bp_user.setting"), code=302)
        return redirect(url_for("bp_user.index"), code=302)


@app.route("/")
def index2():
    return redirect(url_for("bp_user.index"), code=302)


@app.route(nginx + "/")
def index():
    return redirect(url_for("bp_user.index"), code=302)


@app.route(nginx + "/month")
@login_required
def month_eval():
    # flash("正在开发中，请稍等!", category="success")
    # return redirect(url_for('bp_user.index'), code=302)

    userid = current_user.id
    try:
        month = int(request.args.get("month"))
        year = int(request.args.get("year"))
    except:
        flash("What are you doing?", category="danger")
        return redirect(url_for("bp_user.index"), code=302)

    # datas_year = db.session.query(Task.title,Task.tasktime,Task.manhour,Category.name,Subcategory.name,User.no,User.name,Jobnumber.name,Jobnumber.desc).join(User,Task.userid==User.id).join(Category,Task.categoryid==Category.id).join(Subcategory,Task.subcategoryid==Subcategory.id).join(Jobnumber,Task.jobnumberid==Jobnumber.id).filter(Task.userid == userid,Task.delete == False,Task.categoryid != 33, extract('year',Task.tasktime) == year).all()
    datas_month = (
        db.session.query(
            Task.title,
            Task.tasktime,
            Task.manhour,
            Category.name,
            Subcategory.name,
            User.no,
            User.name,
            Jobnumber.name,
            Jobnumber.desc,
        )
        .join(User, Task.userid == User.id)
        .join(Category, Task.categoryid == Category.id)
        .join(Subcategory, Task.subcategoryid == Subcategory.id)
        .join(Jobnumber, Task.jobnumberid == Jobnumber.id)
        .filter(
            Task.userid == userid,
            Task.delete == False,
            Task.categoryid != 33,
            extract("year", Task.tasktime) == year,
            extract("month", Task.tasktime) == month,
        )
        .all()
    )
    # tb01 = [] # 月份考核
    # tb02 = [] # 工时成果统计
    # tb03 = [] # iMES
    # tb01_dict = {}
    # tb02_dict = {}
    # tb03_dict = {}
    # for data in datas_month:
    #     taskDesc, taskTime, taskHour,category,subCategory,userNo,userId,jobNumber,jobName = data

    return render_template("month.html", datas=datas_month)


@app.route(nginx + "/springfestival2019")
def springfestival2019():
    public_weekends = [
        "2019-01-26",
        "2019-01-27",
        "2019-02-04",
        "2019-02-05",
        "2019-02-06",
        "2019-02-07",
        "2019-02-08",
        "2019-02-09",
        "2019-02-10",
        "2019-02-16",
        "2019-02-17",
        "2019-02-23",
        "2019-02-24",
    ]
    start_date = datetime(2019, 1, 28)
    date_range = 19
    categoryid = 33  # 休假id
    data = {}
    end_date = start_date + timedelta(date_range)
    # users = db.session.query(User.id,User.no,User.name,User.position).order_by(User.position).order_by(User.no).all()
    users = (
        db.session.query(User.id, User.no, User.name, User.position)
        .filter(User.name != "admin", User.delete == False)
        .order_by(User.position)
        .order_by(User.no)
        .all()
    )
    tasks = (
        db.session.query(User.id, Task.tasktime, Task.manhour, Subcategory.name)
        .join(Task, Task.userid == User.id)
        .join(Subcategory, Task.subcategoryid == Subcategory.id)
        .filter(
            Task.tasktime >= start_date,
            Task.tasktime <= end_date,
            User.name != "admin",
            Task.categoryid == categoryid,
            Task.delete == False,
        )
        .all()
    )
    for user in users:
        days = {}
        for single_day in (start_date + timedelta(i) for i in range(date_range)):
            single_day_str = single_day.date().__str__()
            if single_day_str in public_weekends:
                day_type = "春节"
            else:
                day_type = " "
            days[single_day_str] = day_type
        user_id, user_no, user_name, user_position = user
        if not data.get(user_id):
            data[user_id] = {
                "no": user_no,
                "name": user_name,
                "position": user_position,
                "tasks": days,
            }
    for task in tasks:
        user_id, task_day, task_hour, subcategory_name = task
        user = data.get(user_id)
        if user:
            if user["tasks"].get(task_day.date().__str__()):
                data[user_id]["tasks"][
                    task_day.date().__str__()
                ] = f"{subcategory_name}"
        else:
            pass
            # print(f"User id {user_id} not found!")
    return render_template("springfestival2019.html", data=data, days=days)


@app.route(nginx + "/springfestival2020")
def springfestival2020():
    public_weekends = [
        "2020-01-24",
        "2020-02-02",
        "2020-02-08",
        "2020-02-09",
        "2020-02-15",
        "2020-02-16",
        "2020-01-18",
        "2020-01-25",
        "2020-01-26",
        "2020-01-27",
        "2020-01-28",
        "2020-01-29",
        "2020-01-30",
    ]
    start_date = datetime(2020, 1, 16)
    date_range = 30
    categoryid = 33  # 休假id
    data = {}
    end_date = start_date + timedelta(date_range)
    # users = db.session.query(User.id,User.no,User.name,User.position).order_by(User.position).order_by(User.no).all()
    users = (
        db.session.query(User.id, User.no, User.name, User.position)
        .filter(User.name != "admin", User.delete == False)
        .filter(~User.id.in_((1, 4, 116, 117, 118)))
        .filter(User.delete == False)
        .order_by(User.position)
        .order_by(User.no)
        .all()
    )
    tasks = (
        db.session.query(User.id, Task.tasktime, Task.manhour, Subcategory.name)
        .join(Task, Task.userid == User.id)
        .join(Subcategory, Task.subcategoryid == Subcategory.id)
        .filter(
            Task.tasktime >= start_date,
            Task.tasktime <= end_date,
            User.name != "admin",
            Task.categoryid == categoryid,
            Task.delete == False,
        )
        .all()
    )
    for user in users:
        days = {}
        for single_day in (start_date + timedelta(i) for i in range(date_range)):
            single_day_str = single_day.date().__str__()
            if single_day_str in public_weekends:
                day_type = "公休"
            else:
                day_type = " "
            days[single_day_str] = day_type
        user_id, user_no, user_name, user_position = user
        if not data.get(user_id):
            data[user_id] = {
                "no": user_no,
                "name": user_name,
                "position": user_position,
                "tasks": days,
            }
    for task in tasks:
        user_id, task_day, task_hour, subcategory_name = task
        user = data.get(user_id)
        if user:
            if user["tasks"].get(task_day.date().__str__()):
                data[user_id]["tasks"][
                    task_day.date().__str__()
                ] = f"{subcategory_name}"
        else:
            pass
            # print(f"User id {user_id} not found!")
    return render_template("springfestival2020.html", data=data, days=days)


def monitor_template():
    from os import path

    extra_dirs = [
        "templates",
    ]
    extra_files = extra_dirs[:]
    for extra_dir in extra_dirs:
        for dirname, dirs, files in os.walk(extra_dir):
            for filename in files:
                filename = path.join(dirname, filename)
                if path.isfile(filename):
                    extra_files.append(filename)
    return extra_files


if __name__ == "__main__":

    app.run(
        host="0.0.0.0",
        port=2000,
        debug=True,
        threaded=True,
        extra_files=monitor_template(),
    )

